package com.xunyin.modules.membersuser.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.xunyin.common.service.impl.BaseServiceImpl;
import com.xunyin.common.utils.QueryHelpPlus;
import com.xunyin.dozer.service.IGenerator;
import com.xunyin.modules.log.domain.TimelongRecord;
import com.xunyin.modules.log.service.mapper.TimelongRecordMapper;
import com.xunyin.modules.maincouponsend.domain.TMainCouponUser;
import com.xunyin.modules.maincouponsend.service.mapper.TmainCouponUserMapper;
import com.xunyin.modules.mainpart.service.TMainPartService;
import com.xunyin.modules.mainpart.vo.TMainPartOnlyNameVo;
import com.xunyin.modules.members.domain.TLayer;
import com.xunyin.modules.members.domain.TMembers;
import com.xunyin.modules.members.service.TMembersService;
import com.xunyin.modules.members.service.mapper.TLayerMapper;
import com.xunyin.modules.membersuser.domain.TMembersUser;
import com.xunyin.modules.membersuser.param.TMembersUserQueryParam;
import com.xunyin.modules.membersuser.service.TMembersUserService;
import com.xunyin.modules.membersuser.service.dto.TMembersUserDto;
import com.xunyin.modules.membersuser.service.dto.TMembersUserQueryCriteria;
import com.xunyin.modules.membersuser.service.mapper.TMembersUserMapper;
import com.xunyin.modules.membersuser.vo.MemberUserTimeLongVo;
import com.xunyin.modules.membersuser.vo.MemberUserVo;
import com.xunyin.modules.membersuser.vo.MembersDiscountVo;
import com.xunyin.modules.user.domain.SysXbAppUser;
import com.xunyin.modules.user.service.SysXbAppUserService;
import com.xunyin.utils.CommonConst;
import com.xunyin.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Author xunyinyunshang  <3594419785@qq.com>
 * @date 2022-09-22
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class TMembersUserServiceImpl extends BaseServiceImpl<TMembersUserMapper, TMembersUser> implements TMembersUserService {

    @Autowired
    private IGenerator generator;

    @Autowired
    private SysXbAppUserService sysXbAppUserService;

    @Autowired
    private TmainCouponUserMapper tmainCouponUserMapper;

    @Autowired
    private TMembersUserMapper tMembersUserMapper;

    @Autowired
    private TMainPartService tMainPartService;

    @Autowired
    private TMembersService tMembersService;

    @Autowired
    private TLayerMapper tLayerMapper;

    @Autowired
    private TimelongRecordMapper timelongRecordMapper;


    @Override
    public Map<String, Object> queryAll(TMembersUserQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<TMembersUser> page = new PageInfo<>(queryAll(criteria));
        //List<TStoreRoomDto> tStoreRoomDto = new ArrayList<>();
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", page.getList());
        map.put("totalElements", page.getTotal());
        return map;
    }

    @Override
    public List<TMembersUser> queryAll(TMembersUserQueryCriteria criteria) {
        return baseMapper.selectList(QueryHelpPlus.getPredicate(TMembersUser.class, criteria));
    }

    @Override
    public Boolean getNewUserCoupons(String openId) {

        List<SysXbAppUser> sysXbAppUserList = sysXbAppUserService.selectSysXbAppUserList(null, openId);
        SysXbAppUser sysXbAppUser = new SysXbAppUser();
        if (sysXbAppUserList != null && sysXbAppUserList.size() > 0) {
            sysXbAppUser = sysXbAppUserList.get(0);
        }

        TMainCouponUser teaMainCouponUser = new TMainCouponUser();
        teaMainCouponUser.setUserPhone(sysXbAppUser.getTelephone());
        teaMainCouponUser.setSourceId(0);
        teaMainCouponUser.setTakeTime(new Date());
        teaMainCouponUser.setStartTime(DateUtil.getCurrentDateTime());
        teaMainCouponUser.setEndTime(DateUtil.addDate(new Date(), Calendar.YEAR, 1));
        teaMainCouponUser.setUseProductType(1);
        //DeductionType = 0 新用户1小时体验券
        teaMainCouponUser.setDeductionType(0);
        teaMainCouponUser.setDeductionNum((double) 1);
        teaMainCouponUser.setReductionNum((double) 0);
        //未使用
        teaMainCouponUser.setUseStatus(CommonConst.ENABLE_FLAG);
        teaMainCouponUser.setCreateTime(new Date());
        teaMainCouponUser.setCreateUserId(0);
        teaMainCouponUser.setStatus(CommonConst.ENABLE_FLAG);
        tmainCouponUserMapper.insert(teaMainCouponUser);

        Boolean flag = sysXbAppUserService.lambdaUpdate()
                .eq(SysXbAppUser::getAppId, openId)
                .set(SysXbAppUser::getUserStatus, CommonConst.ENABLE_FLAG)
                .update();
        return flag;
    }

    /**
     * 获取当前会客厅用户可用时长
     */
    @Override
    public List<TMembersUserDto> getMembersTimelong(Integer mainId, String memberUserPhone) {
/*        List<TMembersUserDto> list = teaMembersUserMapper.getMembersTimelong(mainId,memberUserPhone);
        return list;*/
        LambdaQueryWrapper<TMembersUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TMembersUser::getMainId, mainId);
        wrapper.eq(TMembersUser::getMemberUserPhone, memberUserPhone);
        wrapper.eq(TMembersUser::getStatus, 1);
        List<TMembersUserDto> list = generator.convert(baseMapper.selectList(wrapper), TMembersUserDto.class);
        for (TMembersUserDto tMembersUserDto : list) {
            tMembersUserDto.setMemberUserId(tMembersUserDto.getId());
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<MemberUserVo> getUserMemberInfo(String memberUserPhone, String appId) {
        log.info("getUserMemberInfo -> appId={}", appId);
        TMainPartOnlyNameVo tMainPartOnlyNameVo = tMainPartService.getMainPartByAppId(appId);
        List<MemberUserVo> list = tMembersUserMapper.selectByUserIdAndMainId(memberUserPhone, tMainPartOnlyNameVo.getId());
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean getTransferTimeAndMember(String appId, Integer mainId, Double transferTime, String transPhone, String userPhone) {
        Boolean reFlag = false;
        //log.info("getTransferTimeAndMember -> param = {}", param.toString());
        //String appId = param.getAppId();
        log.info("getTransferTimeAndMember -> appId={}", appId);
        TMainPartOnlyNameVo tMainPartOnlyNameVo = tMainPartService.getMainPartByAppId(appId);
        //Integer mainId = tMainPartOnlyNameVo.getId();
        int Recipient;

        //判断转让的用户是否是相同主体的会员
        MemberUserVo memberUserVo = tMembersUserMapper.selectByTransPhoneAndMainId(transPhone, mainId);
        //不存在当前主体的会员用户时，转让时长可以赠送二级会员并改号码用户成为下线，当存在时，只转让时长
        if (memberUserVo == null) {
            //转让会员等级

            TMembers membersModel = tMembersService.selectByMainId(mainId);

            //增加新会员
            TMembersUser teaMembersUser1 = new TMembersUser();
            teaMembersUser1.setMainId(mainId);
            teaMembersUser1.setMembersDiscount(membersModel.getMembersDiscount().doubleValue());
//            teaMembersUser1.setMembersTransCount(membersModel.getMembersTransCount());
            // 受让人不允许再次转让
            teaMembersUser1.setMembersTransCount(0);
            teaMembersUser1.setMembersTimeLength(BigDecimal.valueOf(transferTime));
            teaMembersUser1.setMemberUserPhone(transPhone);
            teaMembersUser1.setMembersId(membersModel.getId());
            teaMembersUser1.setCreateTime(new Date());
            teaMembersUser1.setStatus(CommonConst.ENABLE_FLAG);
            tMembersUserMapper.insert(teaMembersUser1);
            //并新增上下线
            TLayer teaLayer = new TLayer();
            teaLayer.setMainId(mainId);
            teaLayer.setFirstLayerPhone(userPhone);
            teaLayer.setSecondLayerPhone(transPhone);
            teaLayer.setCreateTime(new Date());
            teaLayer.setStatus(CommonConst.ENABLE_FLAG);
            tLayerMapper.insert(teaLayer);

            Recipient = teaMembersUser1.getId();

        } else {
            //已经是相同主体的会员就增加时长
            BigDecimal transferTime1 = BigDecimal.valueOf(transferTime);
            BigDecimal timeLength = memberUserVo.getMembersTimeLength().add(transferTime1);
            memberUserVo.setMembersTimeLength(timeLength);

            TMembersUser tMembersUser = new TMembersUser();
            BeanUtil.copyProperties(memberUserVo, tMembersUser);
            tMembersUser.setUpdateTime(new Date());

            tMembersUserMapper.updateById(tMembersUser);
            Recipient = tMembersUser.getId();
        }
        //扣除转让人时长
        MemberUserVo tmu = tMembersUserMapper.selectByTransPhoneAndMainId(userPhone, mainId);
        if (tmu.getMembersLevel() == 2) {
            tmu.setMembersTransCount(tmu.getMembersTransCount() - 1);
        }
        TMembersUser tMembersUser = new TMembersUser();
        BeanUtil.copyProperties(tmu, tMembersUser);
        tMembersUser.setUpdateTime(new Date());

        BigDecimal transferTime1 = BigDecimal.valueOf(transferTime);
        //BigDecimal subTimeLength = tMembersUser.getMembersTimeLength().subtract(transferTime1);
        BigDecimal timeLength = tMembersUser.getMembersTimeLength().subtract(transferTime1);
        tMembersUser.setMembersTimeLength(timeLength);
        tMembersUserMapper.updateById(tMembersUser);

        //记录时长转让日志
        TimelongRecord timelongRecord = new TimelongRecord();
        timelongRecord.setMainId(mainId);
        timelongRecord.setSource(2);
        timelongRecord.setTimelong(BigDecimal.valueOf(transferTime));
        timelongRecord.setGiver(tmu.getId());
        timelongRecord.setRecipient(Recipient);
        timelongRecord.setCreateTime(new Date());
        timelongRecord.setStatus(Short.parseShort("1"));
        timelongRecordMapper.insert(timelongRecord);
        reFlag = true;
        return reFlag;
    }

    @Override
    public List<MemberUserTimeLongVo> getTimelongRecord(TMembersUserQueryParam param) {

        List<MemberUserTimeLongVo> timelongRecordList = timelongRecordMapper.getTimelongRecordByUserId(param.getMemberUserId());

        return timelongRecordList;
    }

    @Override
    public MembersDiscountVo getMembersDiscount(Integer mainId, String memberUserPhone) {
        boolean isMembers = false;
        MembersDiscountVo userMembersDiscount = tMembersUserMapper.getMembersDiscountByMainIdAndPhone(mainId, memberUserPhone);
        if (userMembersDiscount != null) {
            isMembers = true;
        }
        userMembersDiscount.setIsMembers(isMembers);
        return userMembersDiscount;
    }
}
